import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useMessageStore = defineStore('message', () => {
  // 搜索历史记录
  const searchHistory = ref([])
  const maxHistoryLength = 10

  // 添加搜索历史
  const addSearchHistory = (query) => {
    // 移除重复项
    const index = searchHistory.value.indexOf(query)
    if (index > -1) {
      searchHistory.value.splice(index, 1)
    }
    
    // 添加到开头
    searchHistory.value.unshift(query)
    
    // 限制历史记录长度
    if (searchHistory.value.length > maxHistoryLength) {
      searchHistory.value.pop()
    }
    
    // 保存到本地存储
    saveSearchHistory()
  }

  // 移除搜索历史项
  const removeSearchHistory = (index) => {
    searchHistory.value.splice(index, 1)
    saveSearchHistory()
  }

  // 清空搜索历史
  const clearSearchHistory = () => {
    searchHistory.value = []
    saveSearchHistory()
  }

  // 保存搜索历史到本地存储
  const saveSearchHistory = () => {
    localStorage.setItem('messageSearchHistory', JSON.stringify(searchHistory.value))
  }

  // 从本地存储加载搜索历史
  const loadSearchHistory = () => {
    const history = localStorage.getItem('messageSearchHistory')
    if (history) {
      try {
        searchHistory.value = JSON.parse(history)
      } catch (error) {
        console.error('加载搜索历史失败:', error)
        searchHistory.value = []
      }
    }
  }

  // 初始化时加载搜索历史
  loadSearchHistory()

  return {
    searchHistory,
    addSearchHistory,
    removeSearchHistory,
    clearSearchHistory
  }
}) 